import json

import requests

from common.yaml_util import read_config_file, read_extract_file


class RequestsUtils:
    session = requests.session()

    def __init__(self, base, base_url):
        self.base_url = read_config_file(base, base_url)
        self.last_headers={}

    def send_request(self, method, url,headers=None, **kwargs):
        self.last_method = str(method).lower()
        self.base_url = self.base_url + url
        if headers and isinstance(headers,dict):
            self.last_headers=self.replace_value(headers)

        for key,value in kwargs.items():
            if key in ["params","data","json"]:
                kwargs[key]=self.replace_value(value)
        res = RequestsUtils.session.request(method=self.last_method, url=self.base_url, headers=self.last_headers,**kwargs)
        return res


    def replace_value(self,data):
        if data and isinstance(data,dict):
            str=json.dumps(data)
        else:
            str=data
        for i in range(1, str.count("{{") + 1):
            if "{{" in str and "}}" in str:
                start_index = str.index("{{")
                end_index = str.index("}}")
                old_value = str[start_index, end_index + 2]
                new_value = read_extract_file(old_value[2:-2])
                str = str.replace(old_value, new_value)
                print(str)
        if data and isinstance(data,dict):
            data=json.loads(str)
        else:
            str=data
        return data

if __name__ == '__main__':
    url = "A={{token}}"
    for i in range(1, url.count("{{") + 1):
        if "{{" in url and "}}" in url:
            start_index = url.index("{{")
            end_index = url.index("}}")
            old_value = url[start_index, end_index + 2]
            new_value = read_extract_file(old_value[2:-2])
            url = url.replace(old_value, new_value)
            print(url)
